const item = [
  {index: 1, text: 1},
  {index: 2, text: 2},
  {index: 3, text: 3},
  {index: 4, text: 4},
]

const ul = document.querySelector('.ul');

ul.addEventListener('dragstart', (event) => { // 鼠标点击开始拖拽
  const target = event.target;

  if (target.classList.contains('drag')) {
    const lis = ul.querySelectorAll('li');
    const index = Array.prototype.indexOf.call(lis, target);
    event.dataTransfer.setData('index', index); // 储存当前索引
  }
});

ul.addEventListener('dragover', (event) => { // 拖拽对象经过容器
  event.preventDefault();

  const target = event.target;
  if (target.classList.contains('drop')) {
    target.classList.add('over');
  }
});

ul.addEventListener('dragleave', () => { // 拖拽对象离开容器
  event.preventDefault();

  const target = event.target; // 触发对象是类名为drop的元素
  if (target.classList.contains('drop')) {
    target.classList.remove('over');
  }
});

ul.addEventListener('drop', (event) => {
  event.preventDefault();
  const target = event.target;
  if (target.classList.contains('drop')) {
    target.classList.remove('over');

    const lis = ul.querySelectorAll('li');
    const index = event.dataTransfer.getData('index'); // 取出存入索引
    const drop = lis[index -1];

    if (drop !== target) {
      const li = lis[index];
      ul.insertBefore(drop, target);
      ul.insertBefore(li, target);
    }
  }
});

// 输出新索引
document.querySelector('.btn').addEventListener('click', () => {
  // 获取重新排序后的.drag 元素
  const lis = document.querySelectorAll('.drag');

  lis.forEach((it, i) => {
    // 赋值 当前索引
    const index = it.getAttribute('data-index');
    item[index].index = i +1;
  })
  console.log(item);
});